﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Wq.Extensions.Common
{
    /// <summary>
    /// 枚举类型 JSON转化
    /// </summary>
    public class EnumConverter : JsonConverter
    {
        /// <summary>
        /// 是否可读
        /// </summary>
        public override bool CanRead => false;
        /// <summary>
        /// 写 JSON属性
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var v = (int)value;
            writer.WriteValue(v);
            var text = EnumHelper.ToDescription((Enum)value);
            if (!string.IsNullOrEmpty(text))
            {
                var name = writer.Path.Substring(writer.Path.LastIndexOf(".") + 1) + "Desc";
                writer.WritePropertyName(name);
                writer.WriteValue(text);
            }
        }

        /// <summary>
        /// 读取 JSON属性
        /// </summary>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 是否可转化
        /// </summary>
        /// <param name="type"></param>
        public override bool CanConvert(Type type)
        {
            if (!type.IsEnum)
                return false;
            if (type.FullName == "System.Security.SecurityRuleSet")
                return false;
            return true;
        }
    }
}
